<template>
  <a-modal :title="t['新增']" :footer="false" v-model:visible="visible" width="800px">
    <a-card>
      <a-form :model="form" ref="formRef" @submit-success="submit" :rules="rules">
        <a-form-item field="skinName" :label="t['主题名称']">
          <div class="w-[300px]">
            <a-input allow-clear v-model="form.skinName"></a-input>
          </div>
        </a-form-item>
        <a-form-item :label="t['分类']" field="category">
          <div class="w-[300px]">
            <theme-category-selector
              class="w-full"
              multiple
              :scoped="ENUM_DATA_SCOPE.THIS_SHOP"
              v-model="form.category"
            ></theme-category-selector>
          </div>
        </a-form-item>
        <a-form-item label="主题来源">
          <Scope
            @change="refreshTheme"
            v-model="themeScope"
            :include="['-', '5']"
            class="w-[200px]"
          ></Scope>
        </a-form-item>
        <a-form-item :label="t['匹配主题']" field="groupsId">
          <!-- <a-input v-model="form.groupsId"></a-input> -->
          <lcd-theme-selector
            class="w-[300px]"
            @change="setGroup"
            v-model="form.groupsId"
            ref="themeSelectorRef"
            :scope="themeScope"
            :disabled="!!form.skinId"
          ></lcd-theme-selector>
        </a-form-item>
        <a-form-item :label="t['添加素材']" name="skinList" v-if="!!form.groupsId">
          <ul class="flex gap-2">
            <li @click="selectBackground(item)" v-for="(item, key) in form.skinList">
              <div class="source-item">
                <IconPlus v-if="!item.background" />
                <template v-if="item.background">
                  <img :src="item.background" class="w-full h-full" alt="" />
                  <div class="actions">
                    <a-button :shape="'circle'" @click.stop="item.background = ''">
                      <IconDelete />
                    </a-button>
                  </div>
                </template>
              </div>
              <div class="text-center">
                <div v-if="key === 0">{{ t["封面"] }}</div>
                <div v-else>{{ t["商品数量"] }}-{{ key }}</div>
              </div>
            </li>
          </ul>
        </a-form-item>

        <a-form-item :label="t['预览']" v-if="form.groupsId">
          <ul class="flex gap-2">
            <li @click="setPreview(item)" v-for="(item, key) in form.skinList">
              <div class="source-item">
                <IconPlus v-if="!item.preview" />
                <template v-if="item.preview">
                  <img :src="item.preview" class="w-full h-full" alt="" />
                  <div class="actions">
                    <a-button :shape="'circle'" @click.stop="item.preview = ''">
                      <IconDelete />
                    </a-button>
                  </div>
                </template>
              </div>
              <div class="text-center">
                <div v-if="key === 0">{{ t["封面"] }}</div>
                <div v-else>{{ t["商品数量"] }}-{{ key }}</div>
              </div>
            </li>
          </ul>
        </a-form-item>
        <a-row>
          <a-col :offset="4">
            <a-button :disabled="!form.groupsId" type="primary" htmlType="submit"
              >{{ t["确定"] }}
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <FileSelector @change="setUri" type="0" v-model:visible="selectorVisible" />
  </a-modal>
</template>

<script setup lang="ts">
import { Library } from "@/api/service/library/types";
import { addSkins, ISkin, ISkinItem, updateSkins } from "@/api/service/skin";
import { QueryTheme } from "@/api/service/theme/types";
import LcdThemeSelector from "@/components/selector/LcdThemeSelector.vue";
import { ENUM_DATA_SCOPE } from "@/enum/system.enum";
import FileSelector from "@/views/admin/components/file-selector/FileSelector.vue";
import { FieldRule } from "@arco-design/web-vue";
import { IconDelete, IconPlus } from "@arco-design/web-vue/es/icon";

const themeSelectorRef = ref<typeof LcdThemeSelector>();
let rawObj = {
  skinId: "",
  skinName: "",
  category: [],
  priority: 0,
  func: "",
  groupsId: "",
  skinList: [],
  previewList: []
};

const themeScope = ref(ENUM_DATA_SCOPE.THIS_SHOP);
const props = defineProps<{
  formData?: ISkin;
}>();

const mode = ref<"background" | "preview">("background");
const current = ref<ISkinItem>({
  skinIndex: 0,
  background: "",
  texture: null,
  preview: ""
});

const form = ref<ISkin>(useCloned(rawObj).cloned.value);
const selectorVisible = ref();
const visible = defineModel<boolean>();
const t = translate("公共模块");
const emit = defineEmits(["submit"]);
const formRef = ref();

const setGroup = async (data: QueryTheme) => {
  form.value.skinList = [];
  form.value.groupsId = data.groupsId;
  data.items.forEach((v, k) => {
    const skinItem: ISkinItem = {
      skinIndex: k,
      background: "",
      texture: null,
      preview: ""
    };
    form.value.skinList.push(useCloned(skinItem).cloned.value);
  });
};

const reset = () => {
  nextTick(() => {
    form.value.skinList = [];
    formRef.value?.resetFields();
    form.value = {
      ...rawObj
    };
  });
};
const refreshTheme = () => {
  themeSelectorRef.value?.fetchLCDThemeCategory();
};
const setUri = (data: Library[]) => {
  const source = data[0];
  if (mode.value === "background") {
    current.value.background = source.uri;
  } else {
    current.value.preview = source.uri;
  }
};
const selectBackground = (item: ISkinItem) => {
  selectorVisible.value = true;
  current.value = item;
  mode.value = "background";
};

const setPreview = (item: ISkinItem) => {
  selectorVisible.value = true;
  mode.value = "preview";
  current.value = item;
};
onMounted(() => {
  reset();
});

const submit = async () => {
  let _form = {
    ...form.value,
    category: (form.value.category as string[])?.join(",")
  };
  if (!props.formData) {
    await addSkins(_form);
  } else {
    await updateSkins(_form);
  }
  reset();
  emit("submit");
  visible.value = false;
};

const rules: Record<keyof ISkin, FieldRule[]> = {
  skinName: [{ required: true }],
  skinId: [],
  category: [],
  priority: [],
  func: [],
  groupsId: [{ required: true }],
  skinList: [{ required: true }]
};

watch(visible, (v) => {
  if (v) {
    Object.assign(form.value, props.formData);
  } else {
    reset();
  }
});
</script>

<style lang="scss" scoped>
li {
  .source-item {
    @apply h-[120px] flex justify-center items-center bg-slate-300 w-[84px] cursor-pointer relative;
    .actions {
      @apply absolute right-0 bottom-0 z-10  h-fit text-red-600 p-2;
    }
  }
}
</style>
